import { asyncRoutes, constantRoutes, defaultRoutes, errorRoutes, Route, router } from '@/router';
import { Info } from '@/store/modules/account/info';
import { Module } from 'vuex';
import { State } from '@/store';
import {
  filterAsyncRoutes,
  filterRoutes,
  menu,
  RESET_STATE,
  resetRoutes,
  SET_STATE,
  time,
} from '@/store/modules/routes/pool';
import { filter, getPaths, mergeRoutes } from '@/router/authority';
import { resetRouter } from '@/router/decorateRouter';
import { accessResourceService } from '@/services/authorization/AccessResource';
import { HttpUtil } from '@/utils/HttpUtil';

export interface RouteState {
  filterRoutes: Route[];
  time: string | null;
}

export const routes: Module<RouteState, State> = {
  namespaced: true,
  state: () => ({
    filterRoutes: [],
    time: null,
  }),
  getters: {
    [filterRoutes]: state => state.filterRoutes,
    [menu]: state => state.filterRoutes.filter(route => route.children && route.children.length > 0),
    [time]: state => state.time,
  },
  mutations: {
    [RESET_STATE]: state => {
      Object.assign(state, {
        filterRoutes: defaultRoutes,
        time: null,
      });
    },
    [SET_STATE]: (state, newState: RouteState) => {
      // console.log('set vuex routes');
      // console.log(newState);
      Object.assign(state, newState);
      // console.log(state);
    },
  },
  actions: {
    async [filterAsyncRoutes]({ commit }, info: Info) {
      // console.log('dispatch');
      // const addRoutes = await filter(asyncRoutes, info);
      let addRoutes: Route[] = [];
      try {
        const resp = await accessResourceService.searchPathAuthorities(getPaths(asyncRoutes));
        if (HttpUtil.isOk(resp)) {
          addRoutes = await filter(asyncRoutes, info, [], HttpUtil.getData(resp));
        }
      } catch (e) {
        console.log(e);
      }
      // console.log('addRoutes', addRoutes);
      const filterRoutes = mergeRoutes(constantRoutes, errorRoutes, addRoutes);
      commit(SET_STATE, {
        filterRoutes: filterRoutes,
        time: info.time,
      });
      // console.log('add routes');
      // console.log(filterRoutes);
      filterRoutes.forEach(route => router.addRoute(route));
      // await router.replace(router.currentRoute.value.path);
      // console.log('reload');
      return filterRoutes;
    },
    [resetRoutes]({ commit }) {
      resetRouter();
      commit(RESET_STATE);
      // console.log('reset routes');
    },
  },
};
